import {AssetType} from './Asset.js';

export class AssetManager {

    static _instance = null;
    static getInst() {
        if (AssetManager._instance instanceof AssetManager) {
            return AssetManager._instance;
        }
        AssetManager._instance = new AssetManager();
        return AssetManager._instance;
    }

    loadList = [];
    loadIndex = 0;
    loadedCount = 0;
    loadFailCount = 0;
    loadLocked = false;
    waitLoadList = [];
    onProgress = null;
    onComplete = null;

    assets = new Map();

    constructor() {
    }

    getAsset(path) {
        let asset = this.assets.get(path);
        return asset;
    }

    loadAssets(loadList, onProgress, onComplete) {
        if (loadList == null || loadList.length <= 0) return;
        if (this.loadLocked == true) {
            this.waitLoadList.push(...loadList);
            return;
        }
        this.loadList = loadList;
        this.onProgress = onProgress;
        this.onComplete = onComplete;
        this.loadLocked = true;
        for (var i = 0; i < this.loadList.length; i++) {
            var item = this.loadList[i];
            this.loadItem(item);
        }
    }

    loadItem(item) {
        var self = this;
        if (item.type == AssetType.IMAGE) {
            var image = new Image();
            image.src = item.path;
            image.onload = function() {
                self.loadedCount += 1;
                item.image = image;
                self.assets.set(item.path, item);
                let progress = self.loadedCount / self.loadList.length;
                self.onProgress && self.onProgress(progress);
                image.onload = null;
                image.onerror = null;
                self.checkLoadProgress();
            }
            image.onerror = function() {
                item.image = null;
                image.onload = null;
                image.onerror = null;
                console.error("AssetManager.loadItem: load fail, path = " + item.path);
                self.loadFailCount += 1;
                self.checkLoadProgress();
            }
        } else {
            self.loadFailCount += 1;
            self.checkLoadProgress();
        }
    }

    checkLoadProgress() {
        if (this.loadedCount + this.loadFailCount >= this.loadList.length) {
            this.loadLocked = false;
            this.onComplete && this.onComplete(this.loadedCount, this.loadList.length);
            this.loadList = null;
            if (this.waitLoadList != null && this.waitLoadList.length > 0) {
                this.loadAssets(this.waitLoadList);
                this.waitLoadList = [];
            }
        }
    }

};

const Res = AssetManager.getInst();
export default Res;